import 'package:flutter/material.dart';
import 'package:fluro/fluro.dart';
// import 'package:fluro_fork/fluro_fork.dart';
import 'package:hkzf/model/user.dart';
import 'package:hkzf/utils/string_is_null_or_empty.dart';
import 'package:provider/provider.dart';
import './routes.dart';
import 'model.dart';
import 'utils/store.dart';

// import 'pages/login.dart';

class Application extends StatelessWidget {
  Application({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Router router = Router();
    Routes.configureRoutes(router);
    return ProviderModel(
      child: Builder(
        builder: (BuildContext context) {
          return App(router: router);
        },
      ),
    );
  }
}

class App extends StatefulWidget {
  const App({
    Key key,
    @required this.router,
  }) : super(key: key);

  final Router router;

  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  // 初始化token,从缓存中读取
  getUserInfo() async {
    var store = await Store.getInstance();
    var token = await store.getString(StoreKeys.token);
    Map<String, dynamic> userInfo = await store.getMap(StoreKeys.userInfo);
    if (!stringIsNullOrEmpty(token)) {
      Provider.of<UserInfo>(context, listen: false).setToken(token); //设置全局用户信息
      Provider.of<UserInfo>(context, listen: false)
          .setUserInfo(userInfo); //设置全局用户信息
    }
  }

  @override
  void initState() {
    super.initState();
    // 初始化token
    getUserInfo();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // home: LoginPage(),
      theme: ThemeData(
        primaryColor: Colors.green,
      ),
      onGenerateRoute: (RouteSettings settings) {
        // 获取provider中的token并判断是否需要拦截
        String token = Provider.of<UserInfo>(context, listen: false).token;
        if (stringIsNullOrEmpty(token) && settings.name != '/login') {
          if (Routes.notNeedLogin.indexOf(settings.name) == -1) {
            return widget.router.generator(RouteSettings(
                name: '/login', arguments: {'redirect': settings}));
          }
        }
        return widget.router.generator(settings);
      },
    );
  }
}
